#!/bin/bash
#This omnipresent conditional is at the beginning of nearly every nci script for checking that current directory is initialized.
if [ ! -d "entries" ]; then
	echo "You haven't initialized nci system yet... Please use \"./init\" before posting a new entry."
	exit 1
fi
if [ ! -f "user.conf" ]; then
	echo "\"user.conf\" file doesn't exist, please run \"./init\" (your existing files won't be affected)"
	exit 1
fi

title=""
entry_number=0
next=0
entry_date=$(date +%m-%d-%Y)
#Prompt user for the article title
echo "New article/entry title:"
read -r title
while [ -z "$title" ]; do
	echo "Error: Empty title. Please try again:"
	read -r title
done

#count created (and deleted) entries
for file in entries/*
do
    if [ -f "$file" ]; then
        entry_number=$((entry_number+1))
	next=$((next+1))
    fi
done
entry_number=$((entry_number-1)) #exclude README file

editor=""
#create the new entry file
touch "entries/entry_$next"
echo "TITLE:$title
DATE:$entry_date
BODY:" >> entries/entry_$next
#read preferred editor
read -r editor < "user.conf"
eval "$editor entries/entry_$next"
echo "-------------------------------------------------"
echo "ENTRY_ID = $next"
echo "TITLE: $title"
echo "DATE: $entry_date"
echo "Article successfully created! REMEMBER: Use \"./refresh\" to insert your new entries into HTML and RSS files."
echo "-------------------------------------------------"
